package service

import (
	"time"

	"github.com/wzh200x/hyperNexus/hyperNexusProtocol/commonProtocol"
	"github.com/wzh200x/webServer/constants"
	Server "github.com/wzh200x/webServer/server"
)

// CDKey使用请求结构
type UseCdKeyRequest struct {
	AvatarId int32  `json:"avatarId" form:"avatarId" binding:"required"` // 角色ID
	Code     string `json:"code" form:"code" binding:"required"`         // CDKey码
}

// CDKey使用响应结构
type CdKeyResponse struct {
	ID          int32  `json:"id"`          // CDKey ID
	Code        string `json:"code"`        // CDKey码
	GroupId     int32  `json:"groupId"`     // CDKey组ID
	CanUseCount int32  `json:"canUseCount"` // 可使用次数
	UsedCount   int32  `json:"usedCount"`   // 已使用次数
	LimitTime   string `json:"limitTime"`   // 限制时间
	CreateTime  string `json:"createTime"`  // 创建时间
	UpdateTime  string `json:"updateTime"`  // 更新时间
}

// CDKey组响应结构
type CdKeyGroupResponse struct {
	ID         int32  `json:"id"`         // CDKey组ID
	Name       string `json:"name"`       // 名称
	Extra      string `json:"extra"`      // 扩展信息
	Desc       string `json:"desc"`       // 描述
	Status     int32  `json:"status"`     // 状态
	CreateTime string `json:"createTime"` // 创建时间
	UpdateTime string `json:"updateTime"` // 更新时间
}

// CDKey使用响应结构
type UseCdKeyResponse struct {
	CdKey      CdKeyResponse      `json:"cdkey"`      // CDKey信息
	CdKeyGroup CdKeyGroupResponse `json:"cdkeyGroup"` // CDKey组信息
}

// UseCdKey 使用CDKey
func UseCdKey(username string, req UseCdKeyRequest) (*UseCdKeyResponse, int, string) {
	// 获取DbAgentServerClient
	dbAgentClient := Server.ServerApp.DbAgentServerClient.GetClientProxy()

	// 查询账号是否存在
	accountQuery := commonProtocol.AccountQuery{
		AccountName: username,
	}
	account, queryErr := dbAgentClient.QueryAccount(accountQuery)
	if queryErr != nil {
		return nil, constants.ErrUnknown, "查询账号失败: " + queryErr.Error()
	}

	// 检查是否有角色
	if account.AvatarId <= 0 && account.HyperNexusAvatarId <= 0 {
		return nil, constants.ErrCharacterNotExist, "角色不存在"
	}

	// 查询角色信息
	avatarQuery := commonProtocol.AvatarQuery{
		AccountName:        username,
		AvatarId:           account.AvatarId,
		HyperNexusAvatarId: account.HyperNexusAvatarId,
	}
	avatar, avatarErr := dbAgentClient.QueryAvatar(avatarQuery)
	if avatarErr != nil {
		return nil, constants.ErrCharacterNotExist, "查询角色失败: " + avatarErr.Error()
	}

	// 查询CDKey是否存在
	cdKeyQuery := commonProtocol.CdKeyQuery{
		Code: req.Code,
	}
	cdKey, cdKeyErr := dbAgentClient.QueryCdKey(cdKeyQuery)
	if cdKeyErr != nil {
		return nil, constants.ErrUnknown, "CDKey不存在: " + cdKeyErr.Error()
	}

	// 检查CDKey是否过期
	limitTime, _ := time.Parse("2006-01-02 15:04:05", cdKey.LimitTime)
	if limitTime.Before(time.Now()) {
		return nil, constants.ErrUnknown, "CDKey已过期"
	}

	// 检查CDKey使用次数是否达到上限
	if cdKey.UsedCount >= cdKey.CanUseCount {
		return nil, constants.ErrUnknown, "CDKey已达到使用上限"
	}

	// 查询玩家是否已使用过该CDKey
	cdKeyUseQuery := commonProtocol.CdKeyUseQuery{
		AccountName:        username,
		AvatarId:           avatar.ID,
		HyperNexusAvatarId: avatar.HyperNexusAvatarId,
		Codes:              []string{req.Code},
	}
	cdKeyUseResp, cdKeyUseErr := dbAgentClient.QueryCdKeyUse(cdKeyUseQuery)
	if cdKeyUseErr == nil && cdKeyUseResp.UseData != nil && len(cdKeyUseResp.UseData) > 0 {
		return nil, constants.ErrUnknown, "您已使用过该CDKey"
	}

	// 更新CDKey使用次数
	cdKey.UsedCount++
	updatedCdKey, updateErr := dbAgentClient.UpdateCdKey(cdKey)
	if updateErr != nil {
		return nil, constants.ErrUnknown, "更新CDKey使用次数失败: " + updateErr.Error()
	}

	// 创建CDKey使用记录
	cdKeyUse := &commonProtocol.CdKeyUse{
		AvatarId:           avatar.ID,
		HyperNexusAvatarId: avatar.HyperNexusAvatarId,
		Codes:              []string{req.Code},
	}
	cdKeyUseCreateOrUpdate := commonProtocol.CdKeyUseCreateOrUpdate{
		AccountName: username,
		CdKeyUse:    cdKeyUse,
	}
	_, createUseErr := dbAgentClient.CreateCdKeyUse(cdKeyUseCreateOrUpdate)
	if createUseErr != nil {
		return nil, constants.ErrUnknown, "创建CDKey使用记录失败: " + createUseErr.Error()
	}

	// 查询CDKey组信息
	cdKeyGroupQuery := commonProtocol.CdKeyGroupQuery{
		ID: cdKey.GroupId,
	}
	cdKeyGroup, groupErr := dbAgentClient.QueryCdKeyGroup(cdKeyGroupQuery)
	if groupErr != nil {
		return nil, constants.ErrUnknown, "查询CDKey组信息失败: " + groupErr.Error()
	}

	// 构建响应
	response := &UseCdKeyResponse{
		CdKey: CdKeyResponse{
			ID:          updatedCdKey.ID,
			Code:        updatedCdKey.Code,
			GroupId:     updatedCdKey.GroupId,
			CanUseCount: updatedCdKey.CanUseCount,
			UsedCount:   updatedCdKey.UsedCount,
			LimitTime:   updatedCdKey.LimitTime,
			CreateTime:  updatedCdKey.CreateTime,
			UpdateTime:  updatedCdKey.UpdateTime,
		},
		CdKeyGroup: CdKeyGroupResponse{
			ID:         cdKeyGroup.ID,
			Name:       cdKeyGroup.Name,
			Extra:      cdKeyGroup.Extra,
			Desc:       cdKeyGroup.Desc,
			Status:     cdKeyGroup.Status,
			CreateTime: cdKeyGroup.CreateTime,
			UpdateTime: cdKeyGroup.UpdateTime,
		},
	}

	return response, 0, ""
}
